import jwt
import time
from django.conf import settings
from django.http import JsonResponse

from user.models import User


def make_token(username, expire=86400):
    key = settings.DASHOPT_KEY
    payload = {
        'exp': time.time() + expire,
        'username': username
    }

    # 使用模块生成token
    return jwt.encode(payload, key, "HS256")


# 装饰器验证用户的l登录状态
def check_login(func):
    def wapper(request, *args, **kwargs):
        # 获取token
        token = request.headers.get("Authorization")
        if not token:
            return JsonResponse({'code': 403, 'error': "请先登录！"})

        # 验证token
        try:
            payload = jwt.decode(token, settings.DASHOPT_KEY, "HS256")
        except Exception as e:
            return JsonResponse({'code': 403, 'error': "请先登录！"})

        # 获取登录的用户对象，通过request给sh被装饰的视图函数
        user_name = payload.get('username')
        user = User.objects.get(user_name=user_name)
        request.login_user = user
        return func(request, *args, **kwargs)

    return wapper
